import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { message, Modal } from 'antd';
import { useNavigate } from 'react-router-dom';
import { isLoggedIn, getUserId } from '../utils/auth';
import { QRCodeSVG as QRCode } from 'qrcode.react';
import { http, host, port } from '../utils/host'
import { LeftOutline } from 'antd-mobile-icons'

// 定义接口
interface Plan {
  name: string;
  price: number;
  description: string;
}

interface OrderInfo {
  orderId: string;
  amount: number;
}

const VipRecharge: React.FC = () => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState<boolean>(false);
  const [paymentMethod, setPaymentMethod] = useState<'wechat' | 'alipay'>('wechat');
  const [showQrCode, setShowQrCode] = useState<boolean>(false);
  const [qrCodeUrl, setQrCodeUrl] = useState<string>('');
  const [orderInfo, setOrderInfo] = useState<OrderInfo | null>(null);
  const [paymentStatus, setPaymentStatus] = useState<'pending' | 'success' | 'failed'>('pending');

  // 会员套餐价格
  const plans: Record<string, Plan> = {
    monthly_vip: { name: '月会员', price: 25, description: '每天可发布10次表白' },
    quarterly_vip: { name: '季会员', price: 45, description: '每天可发布10次表白' },
    vote_ticket: { name: '投票券', price: 5, description: '获得5张投票券' }
  };
  const [selectedPlan, setSelectedPlan] = useState<'monthly_vip' | 'quarterly_vip' | 'vote_ticket'>('monthly_vip');

  // 检查用户是否已登录
  useEffect(() => {
    if (!isLoggedIn()) {
      message.warning('请先登录');
      navigate('/login');
    }
  }, [navigate]);

  // 创建订单并生成支付二维码
  const handleRecharge = async (): Promise<void> => {
    if (!isLoggedIn()) {
      message.warning('请先登录');
      navigate('/login');
      return;
    }

    setLoading(true);
    try {
      const userId = getUserId();
      const response = await axios.post<{ orderId: string; amount: number; paymentUrl: string }>(`${http}${host}${port}/api/vip/create-order`, {
        userId,
        productType: selectedPlan,
        paymentMethod
      });

      // 保存订单信息并生成支付二维码
      setOrderInfo({
        orderId: response.data.orderId,
        amount: response.data.amount
      });
      setQrCodeUrl(response.data.paymentUrl);
      console.log('支付链接:', response.data.paymentUrl);
      setShowQrCode(true);
    } catch (error) {
      console.error('创建订单失败:', error);
      message.error(error.response?.data?.message || '创建订单失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  // 关闭二维码弹窗
  const handleCloseQrCode = (): void => {
    setShowQrCode(false);
    setPaymentStatus('pending');
  };

  // 检查支付状态
  const checkPaymentStatus = async (): Promise<void> => {
    if (!orderInfo || paymentStatus !== 'pending') return;

    try {
      const response = await axios.get<{ status: 'paid' | 'failed' | 'pending' }>(`${http}${host}${port}/api/vip/check-payment`, {
        params: { orderId: orderInfo.orderId }
      });

      if (response.data.status === 'paid') {
        setPaymentStatus('success');
        message.success('支付成功，会员已生效');
        setTimeout(() => {
          setShowQrCode(false);
          navigate('/confession-wall');
        }, 2000);
      } else if (response.data.status === 'failed') {
        setPaymentStatus('failed');
        message.error('支付失败，请重试');
      }
    } catch (error) {
      console.error('检查支付状态失败:', error);
    }
  };

  // 监听二维码显示状态，启动定时检查
  useEffect(() => {
    if (showQrCode && paymentStatus === 'pending') {
      const intervalId = setInterval(checkPaymentStatus, 3000); // 每3秒检查一次
      return () => clearInterval(intervalId);
    }
  }, [showQrCode, paymentStatus]);

  // 返回上一页
  const handleGoBack = (): void => {
    navigate(-1);
  };

  // 样式定义
  const styles = {
    container: {
      maxWidth: '600px',
      margin: '0 auto',
      padding: '20px',
      height: '100vh',
      boxSizing: 'border-box'
    },
    header: {
      display: 'flex',
      alignItems: 'center',
      marginBottom: '30px'
    },
    backButton: {
      fontSize: '24px',
      marginRight: '20px',
      cursor: 'pointer'
    },
    title: {
      fontSize: '20px',
      fontWeight: 'bold'
    },
    planCard: {
      border: '1px solid #e8e8e8',
      borderRadius: '8px',
      padding: '20px',
      marginBottom: '15px',
      cursor: 'pointer',
      transition: 'all 0.3s'
    },
    selectedPlan: {
      border: '1px solid #1890ff',
      backgroundColor: '#e6f7ff'
    },
    planName: {
      fontSize: '16px',
      fontWeight: 'bold',
      marginBottom: '5px'
    },
    planPrice: {
      fontSize: '24px',
      color: '#f5222d',
      marginBottom: '5px'
    },
    planDescription: {
      color: '#595959'
    },
    paymentMethodArea: {
      marginTop: '30px',
      marginBottom: '30px'
    },
    paymentMethodLabel: {
      marginRight: '15px',
      cursor: 'pointer'
    },
    rechargeButton: {
      width: '100%',
      backgroundColor: '#1890ff',
      color: 'white',
      border: 'none',
      padding: '12px 0',
      borderRadius: '4px',
      fontSize: '16px',
      cursor: 'pointer'
    },
    disabledButton: {
      backgroundColor: '#d9d9d9',
      cursor: 'not-allowed'
    },
    qrCodeContainer: {
      display: 'flex',
      flexDirection: 'column',
      alignItems: 'center',
      padding: '20px'
    },
    qrCodeImage: {
      margin: '20px 0'
    },
    paymentTip: {
      color: '#595959',
      marginTop: '10px',
      textAlign: 'center'
    }
  };

  return (
    <div style={styles.container}>
      <div style={styles.header}>
        <span style={styles.backButton} onClick={handleGoBack}><LeftOutline /></span>
        <h2 style={styles.title}>会员充值</h2>
      </div>

      <div>
        <h3>选择套餐</h3>
        {Object.keys(plans).map(planKey => (
          <div
            key={planKey}
            style={{ ...styles.planCard, ...(selectedPlan === planKey ? styles.selectedPlan : {}) }}
            onClick={() => setSelectedPlan(planKey)}
          >
            <div style={styles.planName}>{plans[planKey].name}</div>
            <div style={styles.planPrice}>¥{plans[planKey].price}</div>
            <div style={styles.planDescription}>{plans[planKey].description}</div>
          </div>
        ))}
      </div>

      <div style={styles.paymentMethodArea}>
        <h3>支付方式</h3>
        <div style={{ display: 'flex' }}>
          <div
            style={{ ...styles.paymentMethodLabel, color: paymentMethod === 'wechat' ? '#1890ff' : '#333' }}
            onClick={() => setPaymentMethod('wechat')}
          >
            <input
              type="radio"
              checked={paymentMethod === 'wechat'}
              onChange={() => setPaymentMethod('wechat')}
              style={{ marginRight: '5px' }}
            />
            微信支付
          </div>
          <div
            style={{ ...styles.paymentMethodLabel, color: paymentMethod === 'alipay' ? '#1890ff' : '#333' }}
            onClick={() => setPaymentMethod('alipay')}
          >
            <input
              type="radio"
              checked={paymentMethod === 'alipay'}
              onChange={() => setPaymentMethod('alipay')}
              style={{ marginRight: '5px' }}
            />
            支付宝
          </div>
        </div>
      </div>

      <button
        style={{ ...styles.rechargeButton, ...(loading ? styles.disabledButton : {}) }}
        onClick={handleRecharge}
        disabled={loading}
      >
        {loading ? '处理中...' : `立即支付 ¥${plans[selectedPlan].price}`}
      </button>

      {/* 支付二维码弹窗 */}
      <Modal
        title={paymentMethod === 'wechat' ? '微信支付' : '支付宝支付'}
        open={showQrCode}
        onCancel={handleCloseQrCode}
        footer={null}
        centered
      >
        <div style={styles.qrCodeContainer}>
          <p>订单号: {orderInfo?.orderId}</p>
          <p>支付金额: ¥{orderInfo?.amount}</p>
          <div style={styles.qrCodeImage}>
            {paymentStatus === 'pending' ? (
              <QRCode value={qrCodeUrl} size={200} />
            ) : paymentStatus === 'success' ? (
              <div style={{ color: '#52c41a', fontSize: '24px' }}>✓ 支付成功</div>
            ) : (
              <div style={{ color: '#f5222d', fontSize: '24px' }}>✗ 支付失败</div>
            )}
          </div>
          <p style={styles.paymentTip}>
            {paymentStatus === 'pending' ? (
              paymentMethod === 'wechat' ? '请使用微信扫描二维码支付' : '请使用支付宝扫描二维码支付'
            ) : paymentStatus === 'success' ? (
              '支付成功，即将跳转到表白墙...'
            ) : (
              '支付失败，请关闭窗口后重试'
            )}
          </p>
          {paymentStatus === 'pending' && (
            <p style={styles.paymentTip}>支付完成后请等待页面自动跳转</p>
          )}
        </div>
      </Modal>
    </div>
  );
};

export default VipRecharge;